﻿using System.Collections.Generic;
using AudioStudio;
using FlowCanvas.Nodes;
using UnityEngine;

namespace Yoozoo.Gameplay.Liberty.StreetEvent
{
    public class Play3DSound : CallableActionNode<string, string, bool>
    {
        public static Dictionary<string, GameObject> SoundObjectMap;

        private GameObject soundObject;
        private string _audioName;
        private bool _isLoop;
        public override void Invoke(string audioName, string pointName, bool loop)
        {
            if (SoundObjectMap == null)
            {
                SoundObjectMap = new Dictionary<string, GameObject>(10);
            }

            if (!SoundObjectMap.TryGetValue(audioName, out soundObject))
            {
                soundObject = new GameObject(audioName);
                SoundObjectMap.Add(audioName, soundObject);
            }
            
            var point = BlueprintUtils.GetBlueprintPoint(pointName);
            soundObject.transform.position = point.position;
            _audioName = audioName;
            _isLoop = loop;
            if (loop)
            {
                AudioManager.PlaySound(audioName,soundObject);
            }
            else
            {
                AudioManager.PlayVoice(audioName,soundObject);
            }


        }

        public override void OnGraphStoped()
        {
            if (soundObject)
            {
                if (SoundObjectMap.ContainsKey(_audioName))
                {
                    SoundObjectMap.Remove(_audioName);
                }
                
                if (_isLoop)
                {
                    AudioManager.StopSound(_audioName,soundObject);
                }
                GameObject.Destroy(soundObject);
            }
        }
    }
}